package cn.itrigger.dynamic.sql.select.render;

import static cn.itrigger.dynamic.sql.util.StringUtilities.*;

import java.util.*;

/**
 * @author admin
 * @date 2018/9/25
 **/
public class DefaultSelectStatementProvider implements SelectStatementProvider {

    private String queryExpression;
    private Map<String, Object> parameters;
    private Optional<String> orderByClause;

    private DefaultSelectStatementProvider(Builder builder) {
        this.queryExpression = Objects.requireNonNull(builder.queryExpression);
        this.orderByClause = Objects.requireNonNull(builder.orderByClause);
        this.parameters = Collections.unmodifiableMap(builder.parameters);
    }

    @Override
    public Map<String, Object> getParameters() {
        return parameters;
    }

    @Override
    public String getSelectStatement() {
        return queryExpression + spaceBefore(orderByClause);
    }

    public static Builder withQueryExpression(String queryExpression) {
        return new Builder().withQueryExpression(queryExpression);
    }

    public static class Builder {
        private String queryExpression;
        private Map<String, Object> parameters = new HashMap<>();
        private Optional<String> orderByClause = Optional.empty();

        public Builder withQueryExpression(String queryExpression) {
            this.queryExpression = queryExpression;
            return this;
        }

        public Builder withOrderByClause(Optional<String> orderByClause) {
            this.orderByClause = orderByClause;
            return this;
        }

        public Builder withParameters(Map<String, Object> parameters) {
            this.parameters.putAll(parameters);
            return this;
        }

        public DefaultSelectStatementProvider build() {
            return new DefaultSelectStatementProvider(this);
        }
    }
}
